package org.yylnb.openplatform.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;
import org.yylnb.openplatform.commons.bean.LoggerBean;
import org.yylnb.openplatform.gateway.mq.SendLoggerBeanBinder;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

/**
 * 这个过滤器用来保存日志的其他内容
 *
 * @author RainLin
 * @date 2020/8/1 - 11:02
 */
@Component
public class LoggerPostFilter extends ZuulFilter {

    private final ObjectMapper objectMapper;
    private final SendLoggerBeanBinder sendLoggerBeanBinder;

    public LoggerPostFilter(ObjectMapper objectMapper, SendLoggerBeanBinder sendLoggerBeanBinder) {
        this.objectMapper = objectMapper;
        this.sendLoggerBeanBinder = sendLoggerBeanBinder;
    }

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 70;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        LoggerBean loggerBean = new LoggerBean();
        RequestContext context = RequestContext.getCurrentContext();
        //开始时间
        Date startTime = (Date) context.get("startTime");

        try {
            loggerBean.setReceiveTime(startTime);
            loggerBean.setResponseTime(new Date());
            HttpServletRequest request = context.getRequest();
            loggerBean.setApiName(request.getParameter("method"));
            loggerBean.setApp_key(request.getParameter("app_key"));
            loggerBean.setContent(request.getQueryString());
            loggerBean.setServerIp(InetAddress.getLocalHost().getHostAddress());
            loggerBean.setRemoteIP(request.getRemoteAddr());
            String json = objectMapper.writeValueAsString(loggerBean);
            MessageChannel channel = sendLoggerBeanBinder.message_channel();
            //发送数据
            channel.send(new GenericMessage<String>(json));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }
}

